<template>
  <view
    v-if="shenheStatus == 0"
    :class="['search-page', hasPopup ? 'not-scroll' : '']"
  >
    <!-- 搜索式导航 -->
    <searchNav
      :searchValue="searchVal"
      @gotoSearch="gotoSearch"
      @clearSearch="clearSearch"
      @searchChange="searchChange"
      @searchFocus="searchFocus"
      @searchBlur="searchBlur"
      v-if="!isTimeSearch"
    ></searchNav>
    <!-- 时间选择搜索导航 -->
    <timeSearchNav
      v-if="isTimeSearch"
      ref="timeSearchNav"
      :searchValue="searchVal"
      :timeParams="timeParams"
      @gotoSearch="gotoSearch"
      @clearSearch="clearSearch"
      @searchChange="searchChange"
      @searchFocus="searchFocus"
      @searchBlur="searchBlur"
      @handleParams="handleParams"
    ></timeSearchNav>
    <!-- 搜索历史 -->
    <searchHistory
      :searchList="historyList"
      @clearHistory="clearHistory"
      @handleSearchHistory="handleSearchHistory"
      v-if="!haveSearchResult && !searchVal && !haveShop"
    ></searchHistory>
    <!-- 搜索发现 -->
    <searchFind
      :searchList="searchFindList"
      @handleSearchFind="handleSearchFind"
      v-if="!haveSearchResult && !searchVal && !haveShop"
    ></searchFind>
    <!-- 输入内容时模糊匹配的列表 -->
    <focusMatchList
      :searchList="focusList"
      :searchVal="searchVal"
      v-if="onFocus && searchVal"
      @handleSearchShop="searchShop"
      @handleMatchItem="handleMatchItem"
    ></focusMatchList>
    <!-- 带条件筛选的搜索列表 -->
    <searchGoodList
      :goodList="goodList"
      @handleTabCondition="handleTabCondition"
      v-if="haveSearchResult"
    ></searchGoodList>
    <!-- 搜索的店铺列表 -->
    <searchShop v-if="haveShop" :shops="shops"></searchShop>
    <!-- 添加购物车数组 -->
    <goodsAddCart :good="good"></goodsAddCart>
    <!-- 时间选择器 -->
    <timePopup
      ref="timePopup"
      @timeConfirm="timeConfirm"
      @closePopup="hasPopup = false"
    ></timePopup>
  </view>
  
  <Shenhe v-else-if="shenheStatus == 1" :isShowTitle="true"></Shenhe>
</template>
<script>
import searchNav from '../components/searchNav.vue';
import searchHistory from '../components/searchHistory.vue';
import searchFind from '../components/searchFind.vue';
import focusMatchList from '../components/focusMatchList.vue';
import searchGoodList from '../../components/search/searchGoodList.vue';
import searchShop from '../components/searchShop.vue';
import utils from '../../common/utils';
import goodsAddCart from '@/components/diyNew/goodsAddCart/index.vue';
import timeSearchNav from '../components/timeSearchNav.vue';
import timePopup from '@/components/popups/timePopup.vue';

import Shenhe from '@/components/shenhe/shenhe';
export default {
  components: {
    searchNav,
    searchHistory,
    searchFind,
    focusMatchList,
    searchGoodList,
    searchShop,
    goodsAddCart,
    timeSearchNav,
    timePopup,
    Shenhe,
  },
  data() {
    return {
	  mch_id:0,
      searchVal: '', // 搜素内容
      onFocus: false,
      haveSearchResult: false,
      haveShop: false,
      historyList: [], // 搜索历史列表
      goodList: [],
      focusList: [],
      shops: [],
      searchFindList: [],
      page_count: 1,
      total_count: 0,
      page_size: 12,
      sort: 0, // 0：综合 1：时间最新 2：价格(sort_type: 0升序 1倒叙) 3：销量倒叙
      sort_type: 0,
      currentTabCondition: {}, // 当前列表搜索条件
      defaultTabCondition: {
        text: '综合',
        haveSequence: false,
        sequenceTop: 1,
        sequenceDown: 0,
        sort: 0,
      }, // 默认列表搜索条件
      // 添加购物车的商品
      good: {},
      isTimeSearch: false,
      timeParams: {},
      hasPopup: false,
    };
  },
  filters: {},
  computed: {
    // shenheStatus() {
    //   return this.$store.getters['shenheStatus']
    // }
  },
  onShow() {
    this.historyList = this.getHistoryList(!0);
  },
  onLoad(t) {
	  if(t.mch_id){
		  this.mch_id=t.mch_id
	  }
    if (t?.params) {
      this.isTimeSearch = true;
      this.timeParams = JSON.parse(t.params);
      this.haveSearchResult = true;
      if (this.timeParams?.keyword) {
        this.searchVal = this.timeParams.keyword;
        this.$nextTick(() => {
          this.$refs.timeSearchNav.searchVal = this.timeParams.keyword;
        });
      }
      this.getSearchList();
    }
    this.getSearchFindList();
    this.currentTabCondition = this.defaultTabCondition;
    uni.$on('searchAddGoods', this.toAddcart);
  },
  onReachBottom() {
    this.page_count++;
    if (this.page_count > Math.ceil(this.total_count / this.page_size)) return;
    let params = {
      keyword: this.searchVal,
      sort: this.currentTabCondition.sort,
      loadMore: true,
      page: this.page_count,
    };
    if (this.currentTabCondition.sort == 2) {
      params['sort_type'] = this.currentTabCondition.sort_type;
    }
    this.searchRequest(params);
  },
  methods: {
    // api获取搜索发现列表
    getSearchFindList() {
      this.$allrequest.search.getSearchFindList().then(res => {
        if (!res.code && res.data) {
          this.searchFindList = res.data;
        }
      });
    },
    // 清空搜索历史
    clearHistory() {
      this.historyList = [];
      uni.removeStorageSync('search_history_list');
    },
    // 查询搜索列表
    gotoSearch(e) {
      this.searchVal = e.val;
			this.page_count = 1;
      this.getSearchList();
    },
    // 监听搜索条件发生
    searchChange(e) {
      this.searchVal = e.val;
      this.getMatchedList({ keyword: this.searchVal });
    },
    // api请求模糊匹配列表
    getMatchedList(params) {
			this.$allrequest.search.getMatchedList(params).then(res => {
			  if (!res.code && res.data) {
			    this.focusList = res.data;
			  }
			});
		},
    // 监听搜索获取焦点
    searchFocus(e) {
      this.searchVal = e.val;
      this.onFocus = true;
      this.haveSearchResult = false;
      this.haveShop = false;
    },
    // 监听搜索失去焦点
    searchBlur(e) {
      setTimeout(() => {
        this.onFocus = false;
      }, 100);
    },
    // 清空搜索条件
    clearSearch(e) {
    },
    // 搜索店铺
    searchShop() {
      this.haveShop = true;
    },
    // 点击匹配搜索项回调事件
    handleMatchItem(e) {
      this.searchVal = e.val;
			this.page_count = 1;
      this.getSearchList();
    },
    // 点击搜索历史回调事件
    handleSearchHistory(e) {
      this.searchVal = e.item;
			this.page_count = 1;
      this.getSearchList();
    },
    // 点击搜索发现回调事件
    handleSearchFind(e) {
      this.resetCondition();
      this.searchVal = e.item;
			this.page_count = 1;
      this.getSearchList();
    },
    // 点击列表tab搜索条件回调
    handleTabCondition(e) {
      let item = e.item;
      if (item.text === this.currentTabCondition.text && item.text != '价格')
        return;
      this.currentTabCondition = item;
      this.page_count = 1;
      this.getSearchList();
    },
    // 请求前数据处理
    getSearchList() {
      let params = {
        keyword: this.searchVal,
        page: this.page_count,
        sort: this.currentTabCondition.sort || '0',
		mch_id:this.mch_id
      };
      if (
        this.currentTabCondition.text === '价格' &&
        this.currentTabCondition.sort_type != undefined
      ) {
        params['sort_type'] = this.currentTabCondition.sort_type;
      }

      if (this.isTimeSearch) {
        this.hotelSearch({
          start_time: `${this.timeParams.start.year}-${this.timeParams.start.month}-${this.timeParams.start.day}`,
          end_time: `${this.timeParams.end.year}-${this.timeParams.end.month}-${this.timeParams.end.day}`,
          ...params,
        });
        return;
      }
      this.searchRequest(params);
    },
    hotelSearch(params) {
      uni.showLoading({
        title: this.$t('list.search'),
        mask: true,
      });

      this.$allrequest.search.hotelSearch(params).then(res => {
        if (!res.code && res.data) {
          uni.hideLoading();
          this.haveSearchResult = true;
          this.setHistory(params.keyword);
          if (params.loadMore) {
            this.goodList = [...this.goodList, ...res.data.list];
          } else {
            this.goodList = res.data.list;
          }
          this.total_count = res.data.row_count;
        }
      });
    },
    // 调用接口请求搜索数据
    searchRequest(params, type = 'good') {
      uni.showLoading({
        title: this.$t('list.search'),
        mask: true,
      });

      this.$allrequest.search.getSearchList(params).then(res => {
        if (!res.code && res.data) {
          uni.hideLoading();
          this.haveSearchResult = true;
          this.setHistory(params.keyword);
          if (params.loadMore) {
            this.goodList = [...this.goodList, ...res.data.list];
          } else {
            this.goodList = res.data.list;
          }
          this.total_count = res.data.row_count;
        }
      });
    },
    // 重置数据及搜索条件
    resetCondition() {
      this.page_count = 1;
    },
    // 获取搜索历史列表
    getHistoryList(t) {
      t = t || !1;
      var a = uni.getStorageSync('search_history_list');
      if (!a) return [];
      if (!t) return a;
      for (var e = [], s = a.length - 1; 0 <= s; s--) e.push(a[s]);
      return e;
    },
    // 缓存搜素历史
    setHistory(t) {
      if (!t) {
        return;
      }
      var a = this.getHistoryList();
      // 去重
      let same = a.filter(d => {
        return d.keyword == t;
      });
      if (same.length) return;
      for (var e in (a.push({
        keyword: t,
      }),
      a)) {
        if (a.length <= 10) break;
        a.splice(e, 1);
      }
      this.historyList.push({ keyword: t });
      uni.setStorageSync('search_history_list', a);
    },
    // 点击添加购物车
    toAddcart(e) {
      this.good = JSON.parse(JSON.stringify(e));
      setTimeout(() => {
        this.good = {};
      }, 1);
    },
    // 点击时间
    handleParams() {
      this.$refs.timePopup.showPopup();
      this.hasPopup = true;
    },
    timeConfirm(e) {
      this.hasPopup = false;
      this.$refs.timePopup.hidePopup();
      this.timeParams.start = e.start;
      this.timeParams.end = e.end;
    },
  },
};
</script>

<style scoped lang="scss">
.search-page {
  width: 100%;
  min-height: 100vh;
  background-color: #ffffff;
  position: relative;
  font-family: PingFang SC;
}
.not-scroll {
  height: 100vh;
  overflow: hidden;
}
</style>
